<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 优惠券类
 * @package  module
 * @subpackage  base/system
 * @author   allen.qiang
 * @version 1.0
 */
quanli_require('module/base/selector/gSelectorHandler.class.php');
quanli_require('module/base/selector/custSelector.class.php');

class quanliCoupon {

    /**
     * 查询优惠券列表
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return array|null
     */
    public function searchCoupon(&$arg_array) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //优惠券ID
        if (isset($arg_array['couponID']) && is_numeric($arg_array['couponID'])) {
            $sql .= ' AND couponID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['couponID'];
        }

        //优惠券名称
        if(isset($arg_array['couponName']) && !empty($arg_array['couponName']) ){
            $sql .= ' AND couponName LIKE ? ';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['couponName']) . '%';
        }

        //开始日期
        if(isset($arg_array['startDate']) && !empty($arg_array['startDate']) ){
            $sql .= ' AND startDate >= ? ';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'] . ' 00:00:00';
        }

        //结束日期
        if(isset($arg_array['endDate']) && !empty($arg_array['endDate']) ){
            $sql .= ' AND endDate <= ? ';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'] . ' 23:59:59';
        }

        //优惠券发放方式
        if(isset($arg_array['couponType']) && in_array($arg_array['couponType'], array(1, 2, 3)) ){
            $sql .= ' AND couponType = ? ';
            $params_type .= 'i';
            $params_array[] = $arg_array['couponType'];
        }

        //万能码
        if (isset($arg_array['wncode']) && !empty($arg_array['wncode'])) {
            $sql .= ' AND wncode = ? ';
            $params_type .= 's';
            $params_array[] = $arg_array['wncode'];
        }

        //使用标志
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ? ';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        //拓展字段
        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }


        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_coupon ' . $sql;

                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT * FROM promotion_coupon ' . $sql;

            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    if ($item->couponType == 1)
                        $type_name = '编号礼品券';
                    else if ($item->couponType == 2)
                        $type_name = '账户礼品券';
                    else if ($item->couponType == 3)
                        $type_name = '万能码';

                    if( $item->useType == 1 ){
                        $useTypeName = '券';
                    }else if( $item->useType == 2 ){
                        $useTypeName = '红包';
                    }
                    $item_array[] = array(
                        'couponID' => $item->couponID,            //ID
                        'couponName' => $item->couponName,        //名称
                        'startDate' => $item->startDate,          //开始日期
                        'endDate' => $item->endDate,              //结束日期
                        'couponType' => $item->couponType,        //发放方式
                        'type_name' => $type_name,                //发放方式名称
                        'useFlg' => $item->useFlg,                //使用标志
                        'amount' => $item->amount,                //优惠券金额
                        'limitMoney' => $item->limitMoney,        //订单使用限额
                        'wncode' => $item->wncode,                //万能码
                        'totalNum' => $item->totalNum,            //发放数量
                        'validity' => $item->validity,            //有效期
                        'goodsSelector' => $item->goodsSelectorID,  //商品筛选器
                        'userSelector' => $item->userSelectorID,    //用户筛选器
                        'description' => $item->description,      //描述
                        'getNum' => $item->getNum,                //已发放的数目
                        'useNum' => $item->useNum,                //已使用的数目
                        'isGenerate' => $item->isGenerate,         //是否已生成优惠券
                        'useType' => $item->useType,                //优惠券使用类型
                        'code_number'=>$item->code_number,          //券号长度
                        'departmentID'=>$item->departmentID,
                        'departmentName'=>$item->departmentName,
                        'useTypeName'=>$useTypeName,
                        'cityID'=>$item->cityID
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 检查优惠券编号
     * @param string $code 优惠券编号
     * @param int $pcustID 会员号
     * @param array $goods_array 商品数组
     * @return array
     */
    public function checkCoupon( $code, $pcustID, $goods_array ) {

        global $G_SHOP;

        if (!isset($code, $pcustID, $goods_array) || empty($code) || !is_numeric($pcustID) || empty($goods_array)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //实例化商品筛选器类
        $gSelectorHandler = new gSelectorHandler( $G_SHOP->DBCA );

        //实例会员类
        $custSelector = new custSelector( $G_SHOP->DBCA );

        //查询优惠券编号信息
        $arg_array = array(
            'code' => $code
        );
        $coupon_code_array = $this->searchCouponCode( $arg_array );

        if (!$coupon_code_array) {

            //优惠券编号信息没有找到，检查是否是万能码
            $arg_array = array(
                'wncode' => $code,
                'couponType' => 3,
                'useFlg' => 1
            );
            $coupon_array = $this->searchCoupon( $arg_array );

            if (!$coupon_array) {
                return array( 'code' => 404, 'message' => '优惠券不存在' );
            }
            $coupon_array = $coupon_array[0];

            //检查优惠券是否已过期
            if ($coupon_array['endDate'] < date(G_DEFAULT_DATE_FORMAT)) {
                return array( 'code' => 404, 'message' => '优惠券已过期' );
            }


            //================================检查优惠券所能使用的城市start=======================================
            // add 2014-11-04

            $para_array = array(
                'couponID'=>$coupon_array['couponID']
            );

            $promotion_coupon_city_array = $this->searchCouponCity( $para_array );

            if( $promotion_coupon_city_array ){

                $city_array = array();//城市id数组
                foreach( $promotion_coupon_city_array as $val ){
                    array_push( $city_array,$val['cityID']);
                }

                foreach ($goods_array as &$goods) {
                    if( !in_array($goods['cityID'],$city_array) || empty( $city_array ) ){
                        return array( 'code' => 404, 'message' => '优惠券不在允许使用城市范围' );
                    }
                }
            }else{
                return array( 'code' => 404, 'message' => '优惠券不在允许使用城市范围' );
            }
            //================================检查优惠券所能使用的城市end=======================================

        } else {

            //检查是否是当前会员的优惠券

            //mod by allen.qiang 20141021 微信凑单活动优惠劵调整 start
            if (!empty($coupon_code_array['pcustID']) && $coupon_code_array['pcustID'] != $pcustID) {
                return array( 'code' => 404, 'message' => '优惠券已绑定' );
            }
            /*if ($coupon_code_array['couponType'] == 1) {
                if (!empty($coupon_code_array['pcustID']) && $coupon_code_array['pcustID'] != $pcustID) {
                    return array( 'code' => 404, 'message' => '优惠券已绑定' );
                }
            } else {
                if ($coupon_code_array['pcustID'] != $pcustID) {
                    return array( 'code' => 404, 'message' => '优惠券已绑定' );
                }
            }*/
            //mod by allen.qiang 20141021 微信凑单活动优惠劵调整 end

            //检查优惠券是否已过期
            if ($coupon_code_array['endDate'] < date(G_DEFAULT_DATE_FORMAT)) {
                return array( 'code' => 404, 'message' => '优惠券已过期' );
            }

            //检查优惠券是否已使用
            if (!empty($coupon_code_array['billNo'])) {
                return array( 'code' => 404, 'message' => '优惠券已使用' );
            }

            //查询优惠券信息
            $arg_array = array(
                'couponID' => $coupon_code_array['couponID'],
                'useFlg' => 1
            );
            $coupon_array = $this->searchCoupon( $arg_array );

            if (!$coupon_array) {
                return array( 'code' => 404, 'message' => '优惠券不存在' );
            }
            $coupon_array = $coupon_array[0];

            //================================检查优惠券所能使用的城市start=======================================
            // add 2014-11-04
            $para_array = array(
                'couponID'=>$coupon_array['couponID']
            );

            $promotion_coupon_city_array = $this->searchCouponCity( $para_array );
            if( $promotion_coupon_city_array ){

                $city_array = array();//城市id数组
                foreach( $promotion_coupon_city_array as $val ){
                    array_push( $city_array,$val['cityID']);
                }

                foreach ($goods_array as &$goods) {
                    if( !in_array($goods['cityID'],$city_array) || empty( $city_array ) ){
                        return array( 'code' => 404, 'message' => '优惠券不在允许使用城市范围' );
                    }
                }
            }else{
                return array( 'code' => 404, 'message' => '优惠券不在允许使用城市范围' );
            }
            //================================检查优惠券所能使用的城市end=======================================

        }

        //检查会员是否符合条件
        if (!empty($coupon_array['userSelector']) && !$custSelector->isValid($coupon_array['userSelector'], $pcustID)) {
            return array( 'code' => 404, 'message' => '会员不符合使用条件' );
        }

        //符合条件商品总金额、总数量
        $total_money = 0;
        $goods_amount = 0;

        //筛选商品
        foreach ($goods_array as &$goods) {

            if (!empty($coupon_array['goodsSelector']) && !$gSelectorHandler->isValid($coupon_array['goodsSelector'], $goods['postID']))
                continue;

            $total_money += $goods['price'] * $goods['goodsAmount'];
            $goods_amount += $goods['goodsAmount'];

        }

        //没有符合条件的商品
        if ($goods_amount == 0) {
            return array( 'code' => 404, 'message' => '没有符合优惠券条件的商品' );
        }

        //商品金额不满足优惠券使用限额
        if ($total_money < $coupon_array['limitMoney']) {
            return array( 'code' => 404, 'message' => '商品金额不满足优惠券使用限额' );
        }

        //编号优惠券没有绑定会员
        if ($coupon_array['couponType'] == 1 && empty($coupon_code_array['pcustID'])) {
            $update_sql = 'UPDATE promotion_coupon_code SET pcustID = ? WHERE code = ?';
            $G_SHOP->DBCA->stmt_query($update_sql, 'is', $pcustID, $code);
        }

        $couponID = $coupon_array['couponID'];
        $amount = $coupon_array['amount'];

        $return_array = array(
            'code' => 200,
            'message' => 'ok',
            'data' => array(
                'code' => $code,
                'amount' => $amount,
                'couponID' => $couponID,
                'couponType' => $coupon_array['couponType'],
                'couponName' => $coupon_array['couponName'],
                'useType' => $coupon_array['useType']
            )
        );

        return $return_array;

    }

    /**
     * 查询优惠券编号信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return array|null
     */
    public function searchCouponCode( &$arg_array ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //优惠券编号
        if (isset($arg_array['code']) && !empty($arg_array['code'])) {
            $sql .= ' AND code = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['code'];
        }

        //优惠券ID
        if (isset($arg_array['couponID']) && is_numeric($arg_array['couponID'])) {
            $sql .= ' AND couponID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['couponID'];
        }

        //会员号
        if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //类型
        if (isset($arg_array['couponType']) && in_array($arg_array['couponType'], array(1, 2, 3))) {
            $sql .= ' AND couponType = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['couponType'];
        }

        //使用类型：1、券 2、红包
        if (isset($arg_array['useType']) && in_array($arg_array['useType'], array(1, 2, 3))) {
            $sql .= ' AND useType = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useType'];
        }


        //订单号
        if (isset($arg_array['billNo']) && !empty($arg_array['billNo'])) {
            $sql .= ' AND billNo = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['billNo'];
        }

        //是否使用
        if (isset($arg_array['used']) && in_array($arg_array['used'], array(1, 2, 3))) {
            if ($arg_array['used'] == 1) {
                $sql .= ' AND billNo IS NULL AND endDate >= "' . $G_SHOP->sys_date . '"';
            } else if ($arg_array['used'] == 2) {
                $sql .= ' AND billNo IS NOT NULL';
            } else {
                $sql .= ' AND billNo IS NULL AND endDate < "' . $G_SHOP->sys_date . '"';
            }
        }

        //截止日期
        if (isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
            $sql .= ' AND endDate >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_coupon_code ' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT * FROM promotion_coupon_code ' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {

                    $temp_arg_array = array(
                        'couponID' => $item->couponID,
                        'useFlg' => 1
                    );
                    $coupon_array = $this->searchCoupon( $temp_arg_array );
                    if (!$coupon_array) {
                        continue;
                    }

                    $stat = 1;
                    $stat_name = '可使用';
                    if (!empty($item->billNo)) {
                        $stat = 2;
                        $stat_name = '已使用';
                    } else if ($item->endDate < $G_SHOP->sys_date) {
                        $stat = 3;
                        $stat_name = '已过期';
                    }

                    $item_array[] = array(
                        'createTime' => $item->createTime,
                        'code' => $item->code,
                        'couponName' => $coupon_array[0]['couponName'],
                        'couponID' => $item->couponID,
                        'pcustID' => $item->pcustID,
                        'amount' => $item->amount,
                        'endDate' => $item->endDate,
                        'billNo' => $item->billNo,
                        'bill_code' => $item->bill_code,
                        'useTime' => $item->useTime,
                        'useAmount' => $item->useAmount,
                        'remark' => $item->remark,
                        'createTime' => $item->createTime,
                        'couponType' => $item->couponType,
                        'useType' => $item->useType,
                        'limitMoney' => $item->limitMoney,
                        'stat' => $stat,
                        'stat_name' => $stat_name
                    );
                }
            }

            if (isset($arg_array['code']) && !empty($arg_array['code'])) {
                return $item_array[0];
            } else {
                return $item_array;
            }

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 生成优惠券编号
     * @param int $len 编号长度
     * @return string
     */
    public function getCode( $len = 0 ) {

        if ($len == 0) {
            return 'eb' . strtolower(uniqid()) . rand ( 100, 999 );
        } else {
            return get_random_string( $len );
        }

    }

    /**
     * 发放优惠券
     * @param int $couponID 优惠券ID
     * @param array $c_array 会员名数组
     * $c_array = array( '会员名', '会员名', '会员名', '会员名' )
     * @param bool $is_transaction 是否开启事务
     * @return array
     */
    public function createCouponCode( $couponID, $c_array = array(), $is_transaction = true ,$operator) {

        global $G_SHOP;

        //add by allen.qiang 增加操作者信息 start
        if (!isset($operator)) {
            $current_operator= 'system__publish';
        }else{
            $current_operator = $operator;
        }
        //add by allen.qiang 增加操作者信息 end
        if (!isset($couponID) || !is_numeric($couponID)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            if ($is_transaction) {
                $G_SHOP->DBCA->beginTransaction();
            }

            //查询优惠券信息并修改或新增优惠券
            $coupon_obj = new entity('promotion_coupon');
            $coupon_obj->couponID = $couponID;
            if (!$G_SHOP->DBCA->fetch($coupon_obj)) {
                throw new Exception('优惠券信息没有找到', 404);
            }
            if ($coupon_obj->couponType == 3) {
                throw new Exception('万能码优惠券不能生成编号', 404);
            }

            if ($coupon_obj->couponType == 1) { //编号礼品券生产

                if ($coupon_obj->isGenerate == 1) {
                    throw new Exception('优惠券编号已生成', 404);
                }

                //一次生产的优惠券数量
                $num = 5000;

                //循环生生产次数
                $times = ceil( $coupon_obj->totalNum / $num );
                if ($times == 0) {
                    $times = 1;
                }

                //生产优惠券
                $i = 0;

                $already_product_num = 0;

                while($i < $times) {



                    //最后一次循环
                    if($i == $times -1 ){
                        $num = $coupon_obj->totalNum - $already_product_num;
                    }

                    $sql = 'INSERT INTO promotion_coupon_code(uuid,timeStamp,creator,createTime,code,couponID,amount,useType,couponType,limitMoney,endDate) VALUES ';

                    for($j = 0; $j < $num; $j++) {

                        $code = $this->getCode( $coupon_obj->code_number );
                        if ($j == $num - 1) {
                            $sql .= sprintf('("%s","%s","%s","%s","%s",%s,%s,%s,%s,"%s","%s")',
                                make_uuid(), $G_SHOP->sys_datetime, $current_operator,
                                $G_SHOP->sys_datetime, $code, $coupon_obj->couponID, $coupon_obj->amount,$coupon_obj->useType,
                                $coupon_obj->couponType, $coupon_obj->limitMoney, $coupon_obj->endDate);
                        } else {
                            $sql .= sprintf('("%s","%s","%s","%s","%s",%s,%s,%s,%s,"%s","%s"),',
                                make_uuid(), $G_SHOP->sys_datetime,$current_operator,
                                $G_SHOP->sys_datetime, $code, $coupon_obj->couponID, $coupon_obj->amount,$coupon_obj->useType,
                                $coupon_obj->couponType, $coupon_obj->limitMoney, $coupon_obj->endDate);
                        }

                    }

                    if ($G_SHOP->DBCA->execute($sql)) {
                        ++$i;
                        $already_product_num += $num;
                    }

                }

                //更新优惠券信息
                $coupon_obj->isGenerate = 1;
                $G_SHOP->DBCA->save( $coupon_obj );

            } else { //账户礼品券生产

                error_log('优惠券生产时间：' . $G_SHOP->sys_datetime);

                if ($coupon_obj->totalNum == $coupon_obj->getNum) {

                    throw new Exception('优惠券已发放完', 404);
                }
                if ($coupon_obj->totalNum < $coupon_obj->getNum + count($c_array)) {
                    throw new Exception('可发放的优惠券数量不足<br>剩余数量：' . ($coupon_obj->totalNum - $coupon_obj->getNum), 404);
                }
                if (empty($c_array)) {
                    throw new Exception('没有会员数据', 404);
                }



                $getNum = 0;//优惠券已发放数目

                //结束日期
                $day = $coupon_obj->validity-1;
                $endDate = date("Y-m-d", strtotime("$G_SHOP->sys_date   +$day   day"));



                //数组分割成5000一个的小数组
                $chunkData = array_chunk($c_array , 5000);
                $count = count($chunkData);

                error_log('分组数：' . $count);

                for ($i = 0; $i < $count; $i++) {

                    $insert_array = array();

                    foreach($chunkData[$i] as $custID) {

                        $custID = trim($custID);
                        $custID = str_replace('"', '', $custID);

                        //查询会员信息
                        $cust_obj = $G_SHOP->DBCA->stmt_query('SELECT pcustID FROM cust_master WHERE custID = ?', 's', $custID);
                        if (!$cust_obj) {
                            $cust_obj = $G_SHOP->DBCA->stmt_query('SELECT pcustID FROM cust_master WHERE custID = ?', 's', '0' . $custID);
                            if (!$cust_obj) {
                                error_log('会员信息没找到：' . $custID);
                                continue;
                            }
                        }
                        $pcustID = $cust_obj[0]->pcustID;

                        $insert_array[] = sprintf('("%s","%s","%s","%s","%s",%s,%s,%s,%s,%s,"%s","%s")',
                                           make_uuid(), $G_SHOP->sys_datetime, $current_operator,$G_SHOP->sys_datetime,
                                           $this->getCode(), $coupon_obj->couponID, $pcustID, $coupon_obj->amount, $coupon_obj->useType,
                                           $coupon_obj->couponType, $coupon_obj->limitMoney, $endDate);

                        $getNum++;

                    }

                    if (!isset($insert_array[0])) {
                        continue;
                    }
                    error_log('插入数据数量：' . count($insert_array));

                    $insert_sql = 'INSERT INTO promotion_coupon_code(uuid,timeStamp,creator,createTime,code,couponID,pcustID,amount,
                                   useType,couponType,limitMoney,endDate) VALUES ' . implode(',', $insert_array);
                    $j = 1;
                    while($j == 1) {
                        if ($G_SHOP->DBCA->execute($insert_sql)) {
                            error_log('成功：' . $i);
                            $j = 0;
                        } else {
                            error_log('失败：' . $i);
                        }
                    }

                }

                //改变优惠券已发放数量数量
                $coupon_obj->getNum = $coupon_obj->getNum + $getNum;
                $G_SHOP->DBCA->save( $coupon_obj );

            }

            if ($is_transaction) {
                $G_SHOP->DBCA->commit();
            }

            return array( 'code' => 200, 'message' => '优惠券编号生成成功' );

        } catch (Exception $e) {

            if ($is_transaction) {
                $G_SHOP->DBCA->rollBack();
            }

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                echo json_encode( array('code' => 500 ,'message' => '系统错误') );
            }

        }

    }

    /**
     * 回滚已使用的优惠券
     * @param string $coupon_code 优惠券编号
     * @param int $bill_no 订单号
     * @return array
     */
    public function rollbackCoupon( $coupon_code, $bill_no ) {

        global $G_SHOP;

        if (!isset($coupon_code, $bill_no) || empty($coupon_code) || empty($bill_no)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        $code_obj = new entity('promotion_coupon_code');
        $code_obj->code = $coupon_code;

        if (!$G_SHOP->DBCA->fetch($code_obj) || $code_obj->billNo != $bill_no) {

            //检查是否万能码
            $args_array = array(
                'wncode' => $coupon_code
            );
            $coupon_array = $this->searchCoupon( $args_array );
            if ($coupon_array) {
                return array( 'code' => 200, 'message' => 'ok' );
            } else {
                return array( 'code' => 404, 'message' => '优惠券没有找到' );
            }

        }

        $code_obj->billNo = null;
        $code_obj->bill_code = null;
        $code_obj->useTime = null;
        $code_obj->useAmount = null;
        $G_SHOP->DBCA->save( $code_obj );

        return array( 'code' => 200, 'message' => 'ok' );

    }

    /**
     * 变更使用状态
     * @param int $couponID 优惠券ID
     * @return array
     * @throws Exception
     */
    public function changeCouponStatus( $couponID ) {

        global $G_SHOP;

        if (!isset($couponID) || !is_numeric($couponID)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            $coupon_obj = new entity('promotion_coupon');
            $coupon_obj->couponID = $couponID;
            if (!$G_SHOP->DBCA->fetch($coupon_obj)) {
                throw new Exception('优惠券信息没有找到', 404);
            }
            $coupon_obj->useFlg = $coupon_obj->useFlg == 1 ? 0 : 1;
            $G_SHOP->DBCA->save($coupon_obj);

            if ($coupon_obj->useFlg) {
                return array( 'code' => 200, 'message' => '优惠券启用成功' );
            } else {
                return array( 'code' => 200, 'message' => '优惠券禁用成功' );
            }

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                echo json_encode( array('code' => 500 ,'message' => '系统错误') );
            }

        }

    }


    /**
     * 新增或修改优惠券信息
     * @param array $arg_array 优惠券数组
     * @return array
     * @throws Exception
     */
    public function editCoupon( $arg_array ) {

        global $G_SHOP;

        if (!isset($arg_array['couponID'], $arg_array['operator'],$arg_array['cityID']) || !is_numeric($arg_array['couponID']) || empty($arg_array['operator']) || empty($arg_array['cityID']) ) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (!isset($arg_array['couponName']) || empty($arg_array['couponName'])) {
            return array( 'code' => 400, 'message' => '优惠券名不能为空' );
        }

        if (!isset($arg_array['startDate'], $arg_array['endDate']) || !is_date($arg_array['startDate']) || !is_date($arg_array['endDate'])) {
            return array( 'code' => 400, 'message' => '优惠券使用日期不能为空' );
        }if ($arg_array['startDate'] > $arg_array['endDate']) {
            return array( 'code' => 400, 'message' => '开始日期不能大于结束日期' );
        }

        if (!isset($arg_array['couponType']) || !in_array($arg_array['couponType'], array(1, 2, 3))) {
            return array( 'code' => 400, 'message' => '请选择优惠券发放方式' );
        }

        if (!isset($arg_array['useType']) || !in_array($arg_array['useType'], array(1, 2))) {
            return array( 'code' => 400, 'message' => '请选择优惠券使用方式' );
        }

        if (!isset($arg_array['useType']) || !in_array($arg_array['useType'], array(1, 2))) {
            return array( 'code' => 400, 'message' => '请选择优惠券使用方式' );
        }

        if (!isset($arg_array['limitMoney']) || !is_money($arg_array['limitMoney']) || $arg_array['limitMoney'] < 0) {
            return array( 'code' => 400, 'message' => '订单限额不能为空且必须是大于等于0的数字' );
        }

        if (!isset($arg_array['amount']) || !is_money($arg_array['amount']) || $arg_array['amount'] <= 0) {
            return array( 'code' => 400, 'message' => '优惠券抵扣金额不能为空且必须是大于0的数字' );
        }

        if($arg_array['limitMoney'] > 0 && $arg_array['amount'] > $arg_array['limitMoney'] ){
            return array('code'=> 400, 'message'=> '优惠券抵扣金额不能大于订单限额');
        }

        if ($arg_array['couponType'] == 1 ){
            if (!isset($arg_array['code_number']) || !quanli_is_int($arg_array['code_number'])) {
                return array( 'code' => 400, 'message' => '券号长度不能为空且必须是大于0的整数' );
            }
        }
        if ($arg_array['couponType'] == 1 || $arg_array['couponType'] == 2) {
            if (!isset($arg_array['totalNum']) || !quanli_is_int($arg_array['totalNum'])) {
                return array( 'code' => 400, 'message' => '发放数目不能为空且必须是大于0的整数' );
            }

        } else {
            $arg_array['totalNum'] = null;
        }


        if ($arg_array['couponType'] == 2) {

            if (!isset($arg_array['validity']) || !quanli_is_int($arg_array['validity'])) {
                return array( 'code' => 400, 'message' => '有效期不能为空且必须是大于0的整数' );
            }
            $arg_array['wncode'] = null;

        } else if ($arg_array['couponType'] == 3) {

            if (!isset($arg_array['wncode']) || empty($arg_array['wncode'])) {
                return array( 'code' => 400, 'message' => '万能码不能为空' );
            }
            $arg_array['validity'] = 0;

        } else {

            $arg_array['wncode'] = null;
            $arg_array['validity'] = 0;

        }

        if ( !isset($arg_array['goodsSelectorID']) ) {
            $arg_array['goodsSelectorID'] = 0;
        }

        if ( !isset($arg_array['userSelectorID']) ) {
            $arg_array['userSelectorID'] = 0;
        }

        if ( !isset($arg_array['description']) ) {
            $arg_array['description'] = null;
        }

        try {
            $G_SHOP->DBCA->beginTransaction();
            //查询优惠券信息并修改或新增优惠券
            $coupon_obj = new entity('promotion_coupon');
            if ($arg_array['couponID'] > 0) {
                $coupon_obj->couponID = $arg_array['couponID'];
                if (!$G_SHOP->DBCA->fetch($coupon_obj)) {
                    throw new Exception('优惠券信息没有找到', 404);
                }

            } else {

                $coupon_obj->creator = $arg_array['operator'];
                $coupon_obj->isGenerate = 0;
                $coupon_obj->useFlg = 1;
            }
            $coupon_obj->couponName = convertVar($arg_array['couponName']);
            $coupon_obj->startDate = $arg_array['startDate'];
            $coupon_obj->endDate = $arg_array['endDate'];
            $coupon_obj->couponType = $arg_array['couponType'];
            $coupon_obj->amount = $arg_array['amount'];
            $coupon_obj->limitMoney = $arg_array['limitMoney'];
            $coupon_obj->wncode = $arg_array['wncode'];
            $coupon_obj->totalNum = $arg_array['totalNum'];
            $coupon_obj->validity = $arg_array['validity'];
            $coupon_obj->useNum = 0;
            $coupon_obj->goodsSelectorID = $arg_array['goodsSelectorID'];
            $coupon_obj->userSelectorID = $arg_array['userSelectorID'];
            $coupon_obj->description = convertVar($arg_array['description']);

            $coupon_obj->useType = $arg_array['useType'];
            $coupon_obj->code_number = $arg_array['code_number'];
            $coupon_obj->departmentID = $arg_array['departmentID'];
            $coupon_obj->departmentName = $arg_array['departmentName'];

            $G_SHOP->DBCA->save($coupon_obj);

            //保存优惠券对应城市
            if( isset( $arg_array['cityID'] )&& is_array( $arg_array['cityID'] ) ){
                if( isset( $arg_array['couponID'] )&& !empty( $arg_array['couponID'] ) ){
                    //编辑时删除优惠券对应城市
                    $sql = 'DELETE FROM promotion_coupon_city WHERE couponID = ?';
                    $G_SHOP->DBCA->stmt_query( $sql,'i',$arg_array['couponID']);

                    foreach( $arg_array['cityID'] as $val ){
                        $coupon_cityID = new entity('promotion_coupon_city');
                        $coupon_cityID->cityID = $val;
                        $coupon_cityID->couponID = $arg_array['couponID'];
                        $coupon_cityID->couponName = $arg_array['couponName'];
                        $coupon_cityID->creator = $arg_array['operator'];
                        $G_SHOP->DBCA->save( $coupon_cityID );
                    }
                }else{
                    //添加优惠券时获得最大优惠券中id最大的id 即最新添加的优惠券id
                    $sql = 'select MAX(couponID) as couponID FROM promotion_coupon';
                    $couponID_obj = $G_SHOP->DBCA->stmt_query( $sql);
                    $couponID = $couponID_obj[0]->couponID;
                    foreach( $arg_array['cityID'] as $val ){
                        $coupon_cityID = new entity('promotion_coupon_city');
                        $coupon_cityID->cityID = $val;
                        $coupon_cityID->couponID = $couponID;
                        $coupon_cityID->couponName = $arg_array['couponName'];
                        $coupon_cityID->creator = $arg_array['operator'];
                        $G_SHOP->DBCA->save( $coupon_cityID );
                    }
                }

            }else{
                //编辑时清除优惠券对应城市
                if( isset( $arg_array['couponID'] )&& !empty( $arg_array['couponID'] ) ){
                    $sql = 'DELETE FROM promotion_coupon_city WHERE couponID = ?';
                    $G_SHOP->DBCA->stmt_query( $sql,'i',$arg_array['couponID']);
                }
            }

            $G_SHOP->DBCA->commit();

            if ($arg_array['couponID'] > 0) {
                return array( 'code' => 200, 'message' => '优惠券修改成功' );
            } else {
                return array( 'code' => 200, 'message' => '优惠券新增成功' );
            }

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                echo json_encode( array('code' => 500 ,'message' => '系统错误') );
            }

        }

    }

    /**
     * 激活优惠券
     * @param int $pcustID 会员号
     * @param string $coupon_code 优惠券编号
     * @return array
     */
    public function activateCoupon( $pcustID, $coupon_code ) {

        global $G_SHOP;

        quanli_include('module/base/customer/quanliCust.class.php');

        if (!isset($pcustID, $coupon_code) || !quanli_is_int($pcustID)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }
        if (empty($coupon_code)) {
            return array( 'code' => 400, 'message' => '请输入输入优惠券' );
        }

        //实例会员类
        $quanliCust = new quanliCust();

        try {

            $args_array = array(
                'pcustID' => $pcustID
            );
            $customer_array = $quanliCust->searchCustomerDetail( $args_array );
            if (!$customer_array) {
                throw new Exception('会员信息没有找到', 404);
            }

            //查询优惠券并激活
            $coupon_code_obj = new entity('promotion_coupon_code');
            $coupon_code_obj->code = $coupon_code;
            if (!$G_SHOP->DBCA->fetch($coupon_code_obj)) {
                throw new Exception('优惠券没有找到', 404);
            }
            if (!empty($coupon_code_obj->pcustID)) {
                throw new Exception('优惠券已被激活，请检查优惠券', 404);
            }
            $coupon_code_obj->pcustID = $pcustID;
            $G_SHOP->DBCA->save( $coupon_code_obj );

            return array( 'code' => 200, 'message' => '优惠券激活成功' );

        } catch (Exception $e) {
            $G_SHOP->DBCA->rollBack();
            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                echo json_encode( array('code' => 500 ,'message' => '系统错误') );
            }

        }

    }

    /**
     * 返回优惠券编码和金额
     * @param int $couponID 优惠券ID
     * @param bool $is_transaction 是否开启事务
     * @return array coupon_code 优惠劵编码；coupon_money 优惠劵金额
     *  20141021 create by allen.qiang
     */
    public function returnCouponCode( $couponID, $is_transaction = true ) {

        global $G_SHOP;

        if (!isset($couponID) || !is_numeric($couponID)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            if ($is_transaction) {
                $G_SHOP->DBCA->beginTransaction();
            }

            //查询优惠券信息并修改或新增优惠券
            $coupon_obj = new entity('promotion_coupon');
            $coupon_obj->couponID = $couponID;
            if (!$G_SHOP->DBCA->fetch($coupon_obj)) {
                throw new Exception('优惠券信息没有找到', 404);
            }
            if ($coupon_obj->couponType == 3) {
                throw new Exception('万能码优惠券不能生成编号', 404);
            }

            //账户礼品券生产
            if ($coupon_obj->totalNum == $coupon_obj->getNum) {
                throw new Exception('优惠券已发放完', 404);
            }
            if ($coupon_obj->totalNum < $coupon_obj->getNum + 1) {
                throw new Exception('可发放的优惠券数量不足<br>剩余数量：' . $coupon_obj->totalNum - $coupon_obj->getNum, 404);
            }

            $getNum = 0;//优惠券已发放数目

            //结束日期
            $day = $coupon_obj->validity-1;
            $endDate = date("Y-m-d", strtotime("$G_SHOP->sys_date   +$day   day"));
            $code=$this->getCode();//优惠券编码

            $insert_array[] = sprintf('("%s","%s","%s","%s","%s",%s,%s,%s,%s,"%s","%s")',
                make_uuid(), $G_SHOP->sys_datetime, 'system__publish',$G_SHOP->sys_datetime,$code
                , $coupon_obj->couponID, $coupon_obj->amount, $coupon_obj->useType,
                $coupon_obj->couponType, $coupon_obj->limitMoney, $endDate);

            $insert_sql = 'INSERT INTO promotion_coupon_code(uuid,timeStamp,creator,createTime,code,couponID,amount,
                                   useType,couponType,limitMoney,endDate) VALUES ' . implode(',', $insert_array);

            if ($G_SHOP->DBCA->execute($insert_sql)) {
                $getNum++;
            } else {
                $G_SHOP->DBCA->commit();
                return array( 'code' => 400, 'message' => '优惠券编号生成失败' );
            }

            $data=array(
                'coupon_code'=>$code,
                'coupon_money'=>$coupon_obj->amount
            );

            //改变优惠券已发放数量数量
            $coupon_obj->getNum = $coupon_obj->getNum + $getNum;
            $G_SHOP->DBCA->save( $coupon_obj );

            if ($is_transaction) {
                $G_SHOP->DBCA->commit();
            }

            return array( 'code' => 200, 'message' => '优惠券编号生成成功','data'=> $data);

        } catch (Exception $e) {

            if ($is_transaction) {
                $G_SHOP->DBCA->rollBack();
            }

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                echo json_encode( array('code' => 500 ,'message' => '系统错误') );
            }

        }

    }
	//add by 2014-10-29 yim.hu FUN-BK-0010 变更优惠券状态以及插入日志 start
    public function resetCouponStatus( $code ) {
    
    	global $G_SHOP;
    
    	if (!isset($code) ) {
    		return array( 'code' => 400, 'message' => '参数错误' );
    	}
    
    	try {
    
    		$coupon_obj = new entity('promotion_coupon_code');
    		$coupon_obj->code = $code;
    		if (!$G_SHOP->DBCA->fetch($coupon_obj)) {
    			throw new Exception('优惠券信息没有找到', 404);
    		}
    		$coupon_obj->billNo = '';
    		$coupon_obj->bill_code = '';
    		$coupon_obj->useTime = Null;
    		$coupon_obj->useAmount = Null;
    		$coupon_obj->resetCount = $coupon_obj->resetCount+1;
    		$G_SHOP->DBCA->save($coupon_obj);
		
    		//这里开始插入日志
    		//首先读取重置的次数
    		$sql ="select resetCount from promotion_coupon_code where code = '$code'";
    		$result = $G_SHOP->DBCA->stmt_query($sql);
    		//日志类
    		quanli_require('module/base/customer/logHandler.class.php');
            $logHandler = new logHandler( $G_SHOP->DBCA );
    		//退款单日志参数

            $log_array = array(
                'logCategoryID' => 12,//日志分类号
            	'logItem' => '优惠券重置',//日志标题
                'extend_1' => $G_SHOP->currentUserName,//操作人姓名
                'extend_2' => $G_SHOP->currentUserID,//操作人账号
                'extend_3' =>	date('Y-m-d H:i:s',time()),//操作人时间
                'extend_5' =>	$result[0]->resetCount, //具体操作次数
               	'operator' =>  $G_SHOP->currentUserName//创建人姓名
              	
            );
			
            $result_log = $logHandler->saveLogInfo($log_array);
           
    		return array( 'code' => 200, 'message' => '优惠券重置成功' );

    
    	} catch (Exception $e) {
    
    		if ($e->getCode() > 0) {
    			return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
    		} else {
    			error_log($e->getMessage());
    			echo json_encode( array('code' => 500 ,'message' => '系统错误') );
    		}
    
    	}
    
    }
    //add by 2014-10-29 yim.hu FUN-BK-0010 变更优惠券状态以及插入日志 end


    /**
     * 查询优惠券对应城市
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return array|null
     */
    public function searchCouponCity(&$arg_array) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //优惠券ID
        if (isset($arg_array['couponID']) && is_numeric($arg_array['couponID'])) {
            $sql .= ' AND couponID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['couponID'];
        }

        //优惠券名称
        if(isset($arg_array['couponName']) && !empty($arg_array['couponName']) ){
            $sql .= ' AND couponName LIKE ? ';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['couponName']) . '%';
        }

        //城市ID
        if (isset($arg_array['cityID']) && is_numeric($arg_array['cityID'])) {
            $sql .= ' AND cityID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['cityID'];
        }

        //拓展字段
        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }


        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_coupon_city ' . $sql;

                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT * FROM promotion_coupon_city ' . $sql;

            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {

                    $item_array[] = array(
                        'couponID' => $item->couponID,            //ID
                        'couponName' => $item->couponName,        //名称
                        'cityID'=>$item->cityID
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }
}